package com.karry.web;

import com.karry.pojo.*;
import com.karry.service.*;
import com.karry.service.impl.*;
import com.karry.util.ExcelUtil;
import com.karry.util.MailUtil;
import com.karry.util.Page;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.omg.CORBA.ARG_OUT;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("/admin")
public class AdminServlet extends HttpServlet {

    UserService us = new UserServiceImpl();
    BlogService bs = new BlogServiceImpl();
    RecordService rs = new RecordServiceImpl();
    TypeService ts = new TypeServiceImpl();
    CommentService cs = new CommentServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        // 设置首页导航高亮
        //req.setAttribute("menu_page", "index");

        // 得到用户行为 （判断是什么条件查询：标题查询、日期查询、类型查询）
        String actionName = req.getParameter("actionName");
        // 将用户行为设置到request作用域中 （分页导航中需要获取）
        req.setAttribute("action", actionName);

        System.out.println("admin_actionName:" + actionName);

        if (actionName == null){
            actionName = "default";
        }

        switch (actionName){
            case "index":
                goIndex(req, resp);
                break;
            case "user":
                getUserList(req, resp);
                break;
            case "blog":
                getBlogList(req, resp);
                break;
            case "record":
                getRecordList(req, resp);
                break;
            case "type":
                getTypeList(req, resp);
                break;
            case "export":
                try {
                    export(req, resp);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "sendEmail":
                sendEmail(req, resp);
                break;
            case "sendNotify":
                sendNotify(req, resp);
                break;
            case "comment":
                getCommentList(req, resp);
                break;
            default:
                goIndex(req, resp);
                break;
        }


    }

    private void sendNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String text = request.getParameter("text");
        String time = request.getParameter("time");

        if (text == null || text.length() < 3 || text.length() > 128){
            response.getWriter().write(-4 + "");
            return;
        }

        int t = 0;
        if (time == null || time.length() == 0) {
            t = sendN(text);
            System.out.println("群发通知:" + t);
            response.getWriter().write(t + "");
        }else {
            int i = timeTask(us.getAllUserList(), text, 2, time);
            System.out.println("定时群发通知:" + i);
            response.getWriter().write((i - 2) + "");
        }

    }

    private int sendN(String text){
        boolean sF = false, eF = false;
        int t = 0;

        ArrayList<User> allUserList = us.getAllUserList();
        System.out.println("用户列表:" + allUserList.size());
        for (User user : allUserList) {
            System.out.println(user);
            //发送通知就是插入评论，只是不属于任何博客，发送用户也不存在
            Comment comment = cs.insertComment(0, 0, text, 0, user.getId(), "#");
            if (comment != null) {
                sF = true;
            } else {
                eF = true;
            }
        }
        //完全成功
        if (sF && !eF) {
            t = 1;
        } else if (sF) {
            t = 2;
        } else {
            t = 0;
        }
        return t;
    }


    private void getCommentList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //导航栏高亮
        req.setAttribute("menu_page", "comment");
        //ArrayList<User> userList = us.getAllUserList();
        //分页查询
        // 1. 接收参数 （当前页、每页显示的数量）
        String pageNum = req.getParameter("pageNum");

        Page<Comment> commentPage = cs.searchCommentByPage(pageNum, "10");
        User user = (User) req.getSession().getAttribute("user");
        req.setAttribute("page", commentPage);
        req.setAttribute("user", user);
        req.setAttribute("changePage", "commentList.jsp");
        req.getRequestDispatcher("admin/admin.jsp").forward(req, resp);
    }

    private void sendEmail(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        //获取文本
        String text = req.getParameter("text");
        String time = req.getParameter("time");
        System.out.println("time:" + time);

        if (text == null || text.length() < 3 || text.length() > 128){
            resp.getWriter().write(-4 + "");
            return;
        }

        ArrayList<User> allUserList = us.getAllUserList();

        //立刻发送
        if (time == null || time.length() == 0){
            MailUtil mailUtil = new MailUtil();
            int i = mailUtil.sendTextEmail(allUserList, text);
            System.out.println("群发邮件:" + i);
            resp.getWriter().write(i + "");
        }else {
            int i = timeTask(allUserList, text, 1, time);
            System.out.println("定时群发邮件:" + i);
            resp.getWriter().write((i - 2) + "");
        }

    }

    //执行定时任务
    private int timeTask(ArrayList<User> users, String text, int t, String time){
        Timer timer = new Timer();

        //处理时间
        //接收到的时间带这个
        String[] ts = time.split("T");
        int[] localTime = new int[5];
        String[] split = ts[0].split("-");
        for (int i = 0; i < split.length; i++) {
            localTime[i] = Integer.parseInt(split[i]);
        }
        split = ts[1].split(":");
        for (int i = 0; i < split.length; i++) {
            localTime[i + 3] = Integer.parseInt(split[i]);
        }

        if (t == 1){
            //群发邮件
            Date date = new Date(localTime[0]-1900, localTime[1] - 1, localTime[2], localTime[3], localTime[4]);

            //定时不少于5分钟
            if (date.getTime() - System.currentTimeMillis() < (5 * 60 * 1000)){
                return -1;
            }else {
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        MailUtil mailUtil = new MailUtil();
                        int i = mailUtil.sendTextEmail(users, text);
                        timer.cancel();
                    }
                }, date);
            }
            return 1;
        }else {
            //群发邮件
            Date date = new Date(localTime[0]-1900, localTime[1] - 1, localTime[2], localTime[3], localTime[4]);
            //定时不少于5分钟
            if (date.getTime() - System.currentTimeMillis() < (5 * 60 * 1000)){
                return -1;
            }else {
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        sendN(text);
                        timer.cancel();
                    }
                }, date);
            }
            return 1;
        }

    }

    public void export(HttpServletRequest request,HttpServletResponse response) throws Exception {
        exportInfo(request, response);
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {

        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();

            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");

        } catch (Exception ex) {

            ex.printStackTrace();

        }

    }

    private void goIndex(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.getRequestDispatcher("admin/admin.jsp").forward(req, resp);

    }

    private void getUserList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //导航栏高亮
        req.setAttribute("menu_page", "user");
        //ArrayList<User> userList = us.getAllUserList();
        //分页查询
        // 1. 接收参数 （当前页、每页显示的数量）
        String pageNum = req.getParameter("pageNum");
        int index = 1;
        if (pageNum != null && pageNum.length() > 0){
            index = Integer.parseInt(pageNum);
        }
        Page<User> allUserListByPage = us.getAllUserListByPage(index);
        User user = (User) req.getSession().getAttribute("user");
        req.setAttribute("page", allUserListByPage);
        req.setAttribute("user", user);
        req.setAttribute("changePage", "userList.jsp");
        req.getRequestDispatcher("admin/admin.jsp").forward(req, resp);

    }

    private void getBlogList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //导航栏高亮
        req.setAttribute("menu_page", "blog");
        //分页查询
        // 1. 接收参数 （当前页、每页显示的数量）
        String pageNum = req.getParameter("pageNum");
        int index = 1;
        if (pageNum != null && pageNum.length() > 0){
            index = Integer.parseInt(pageNum);
        }
        Page<Blog> blogPage = bs.getAllBlogListByPage(index);
        /*Page<User> allUserListByPage = us.getAllUserListByPage(index);
        req.setAttribute("page", allUserListByPage);*/
        req.setAttribute("page", blogPage);
        req.setAttribute("changePage", "blogList.jsp");
        req.getRequestDispatcher("admin/admin.jsp").forward(req, resp);

    }

    private void getRecordList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //导航栏高亮
        req.setAttribute("menu_page", "record");
        //分页查询
        // 1. 接收参数 （当前页、每页显示的数量）
        String pageNum = req.getParameter("pageNum");
        int index = 1;
        if (pageNum != null && pageNum.length() > 0){
            index = Integer.parseInt(pageNum);
        }
        Page<Record> recordPage = rs.getAllRecordByPage(index);
        req.setAttribute("page", recordPage);
        req.setAttribute("changePage", "recordList.jsp");
        req.getRequestDispatcher("admin/admin.jsp").forward(req, resp);
    }

    private void getTypeList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //导航栏高亮
        req.setAttribute("menu_page", "type");
        //分页查询
        // 1. 接收参数 （当前页、每页显示的数量）
        String pageNum = req.getParameter("pageNum");
        int index = 1;
        if (pageNum != null && pageNum.length() > 0){
            index = Integer.parseInt(pageNum);
        }
        Page<Type> typePage = ts.getAllTypeByPage(index);
        req.setAttribute("page", typePage);
        req.setAttribute("changePage", "typeList.jsp");
        req.getRequestDispatcher("admin/admin.jsp").forward(req, resp);
    }


    //写点死方法
    private void exportInfo(HttpServletRequest request, HttpServletResponse response){

        int index = Integer.parseInt(request.getParameter("table"));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String[] title = new String[0];
        String fileName = null;
        String sheetName = null;
        String[][] content = new String[0][];
        if (index == 1){
            //获取数据
            List<User> list = us.getAllUserList();
            //excel标题
            title = new String[]{"ID", "账号", "昵称", "邮箱", "身份", "状态", "注册时间", "最后登录时间", "最后登录IP"};
            //excel文件名
            fileName = "user"+System.currentTimeMillis()+".xls";
            //sheet名
            sheetName = "用户信息表";
            content = new String[list.size()][title.length];
            for (int i = 0; i < list.size(); i++) {
                content[i] = new String[title.length];
                User obj = list.get(i);
                content[i][0] = String.valueOf(obj.getId());
                content[i][1] = obj.getName();
                content[i][2] = obj.getNick();
                content[i][3] = obj.getEmail();
                if (obj.getRole() == 1){
                    content[i][4] = "用户";
                }else if (obj.getRole() == 2){
                    content[i][4] = "管理员";
                }else {
                    content[i][4] = "超管";
                }
                if (obj.getStatus() == 0){
                    content[i][5] = "删除";
                }else if (obj.getStatus() == 1){
                    content[i][5] = "正常";
                }else {
                    content[i][5] = "封禁";
                }
                String time1 = simpleDateFormat.format(obj.getRegisterTime());
                String time2 = simpleDateFormat.format(obj.getLastLoginTime());
                content[i][6] = time1;
                content[i][7] = time2;
                content[i][8] = obj.getLastLoginIP();
            }
        }else if (index == 2){
            //获取数据
            List<Blog> list = bs.getAllBlog();
            //excel标题
            title = new String[]{"ID", "标题", "作者账号", "文章类型", "发布时间", "最后修改时间", "发布坐标", "是否公开", "状态"};
            //excel文件名
            fileName = "blog"+System.currentTimeMillis()+".xls";
            //sheet名
            sheetName = "博客信息表";
            content = new String[list.size()][title.length];
            for (int i = 0; i < list.size(); i++) {
                content[i] = new String[title.length];
                Blog obj = list.get(i);
                content[i][0] = String.valueOf(obj.getId());
                content[i][1] = obj.getTitle();
                content[i][2] = obj.getUserName();
                content[i][3] = obj.getTypeName();
                String time1 = simpleDateFormat.format(obj.getTime());
                String time2 = simpleDateFormat.format(obj.getLastUpdateTime());
                content[i][4] = time1;
                content[i][5] = time2;
                content[i][6] = "经度：" + obj.getLon() + " 纬度：" + obj.getLan();
                if (obj.getIsOpen() == 1){
                    content[i][7] = "公开";
                }else{
                    content[i][7] = "私密";
                }
                if (obj.getStatus() == 1){
                    content[i][8] = "正常";
                }else {
                    content[i][8] = "删除";
                }

            }
        }else if (index == 3){
            //获取数据
            List<Type> list = ts.searchAllType();
            //excel标题
            title = new String[]{"ID", "所属用户ID", "所属用户类型序号", "名称", "状态"};
            //excel文件名
            fileName = "type"+System.currentTimeMillis()+".xls";
            //sheet名
            sheetName = "博客类型信息表";
            content = new String[list.size()][title.length];
            for (int i = 0; i < list.size(); i++) {
                content[i] = new String[title.length];
                Type obj = list.get(i);
                content[i][0] = String.valueOf(obj.getId());
                content[i][1] = String.valueOf(obj.getUserID());
                content[i][2] = String.valueOf(obj.getUserTypeID());
                content[i][3] = obj.getName();
                if (obj.getStatus() == 1){
                    content[i][4] = "正常";
                }else {
                    content[i][4] = "删除";
                }

            }
        }else if (index == 4){
            //获取数据
            List<Record> list = rs.searchAllRecord();
            //excel标题
            title = new String[]{"ID", "记录类型", "记录所属用户", "记录所属博客", "记录信息", "其他信息", "时间"};
            //excel文件名
            fileName = "record"+System.currentTimeMillis()+".xls";
            //sheet名
            sheetName = "记录信息表";
            content = new String[list.size()][title.length];
            for (int i = 0; i < list.size(); i++) {
                content[i] = new String[title.length];
                Record obj = list.get(i);
                content[i][0] = String.valueOf(obj.getId());
                content[i][1] = String.valueOf(obj.getType());
                if (obj.getUserID() == -1){
                    content[i][2] = "#";
                }else {
                    content[i][2] = String.valueOf(obj.getUserID());
                }
                if (obj.getBlogID() == -1){
                    content[i][3] = "#";
                }else {
                    content[i][3] = String.valueOf(obj.getBlogID());
                }
                content[i][4] = obj.getInfo();
                content[i][5] = obj.getOtherInfo();
                String time = simpleDateFormat.format(obj.getTime());
                content[i][6] = time;
            }
        }else if (index == 5){
            //获取数据
            List<Comment> list = cs.searchAllComment();
            //excel标题
            title = new String[]{"ID", "所属博客", "发表用户", "内容", "所属父评论", "被回复用户", "时间", "被回复内容", "通知", "状态"};
            //excel文件名
            fileName = "comment" + System.currentTimeMillis()+".xls";
            //sheet名
            sheetName = "评论信息表";
            content = new String[list.size()][title.length];
            for (int i = 0; i < list.size(); i++) {
                content[i] = new String[title.length];
                Comment obj = list.get(i);
                content[i][0] = String.valueOf(obj.getId());
                content[i][1] = String.valueOf(obj.getBlogId());
                content[i][2] = String.valueOf(obj.getUserId());
                content[i][3] = String.valueOf(obj.getText());
                content[i][4] = String.valueOf(obj.getFatherCommentId());
                content[i][5] = String.valueOf(obj.getBackUserId());
                String time = simpleDateFormat.format(obj.getTime());
                content[i][6] = time;
                content[i][7] = String.valueOf(obj.getBackCommentText());
                if (obj.getNotify() == 1){
                    content[i][8] = "未阅";
                }else {
                    content[i][8] = "已阅";
                }

                if (obj.getStatus() == 1){
                    content[i][9] = "正常";
                }else {
                    content[i][9] = "删除";
                }
            }
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



}
